package com.green.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.green.business.domain.Provider;
import com.green.business.service.ProviderService;
import com.green.business.vo.GoodsVo;
import com.green.system.common.Constant;
import com.green.system.common.DataGridView;
import com.green.system.domain.Notice;
import com.green.system.mapper.NoticeMapper;
import com.green.system.service.NoticeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.green.business.mapper.GoodsMapper;
import com.green.business.domain.Goods;
import com.green.business.service.GoodsService;
/**
 * Created with IntelliJ IDEA.
 * @Author: Green
 * @Date: 2021/11/15/17:22
 * @Description: 
 */


@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodsService{

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private ProviderService providerService;

    @Autowired
    private NoticeMapper noticeMapper;

    @Override
    public DataGridView queryAllGoods(GoodsVo goodsVo) {
        IPage<Goods> page = new Page<>(goodsVo.getPage(),goodsVo.getLimit());
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(goodsVo.getAvailable() !=null,"available",goodsVo.getAvailable());
        queryWrapper.eq(goodsVo.getProviderid() !=null,"providerid",goodsVo.getProviderid());

        queryWrapper.like(StringUtils.isNotBlank(goodsVo.getGoodsname()),"goodsname",goodsVo.getGoodsname());
        queryWrapper.like(StringUtils.isNotBlank(goodsVo.getSize()),"size",goodsVo.getSize());
        queryWrapper.like(StringUtils.isNotBlank(goodsVo.getProductcode()),"productcode",goodsVo.getProductcode());
        queryWrapper.like(StringUtils.isNotBlank(goodsVo.getPromitcode()),"promitcode",goodsVo.getPromitcode());
        queryWrapper.like(StringUtils.isNotBlank(goodsVo.getDescription()),"description",goodsVo.getDescription());

        this.goodsMapper.selectPage(page,queryWrapper);
        List<Goods> records = page.getRecords();
        for (Goods record : records) {
            if (null != record.getProviderid()){
                Provider provider = this.providerService.getById(record.getProviderid());
                record.setProvidername(provider.getProvidername());
            }
        }

        return new DataGridView(page.getTotal(),page.getRecords());

    }

    @CachePut(cacheNames = "com.green.business.service.impl.GoodsServiceImpl",key = "#result.id")
    @Override
    public Goods updateGoods(Goods goods) {
        Goods selectById = this.goodsMapper.selectById(goods.getId());
        //cachePut方法是更新完后保存更新后的结果，这里param1是需要更新的值，param2是查询的完整值，param3是1赋值2的条件
        BeanUtil.copyProperties(goods,selectById, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        this.goodsMapper.updateById(selectById);
        return selectById;
    }

    @CachePut(cacheNames = "com.green.business.service.impl.GoodsServiceImpl",key = "#result.id")
    @Override
    public Goods saveGoods(Goods goods) {
        this.goodsMapper.insert(goods);
        return goods;
    }

    @Override
    public DataGridView getAllAvailableGoods() {
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("available", Constant.AVAILABLE_TRUE);
        List<Goods> goods = this.goodsMapper.selectList(queryWrapper);
        return new DataGridView(goods);
    }

    @Override
    public Integer selectMaxGoodsId() {
        return (this.goodsMapper.selectMaxGoodsId() + 1);
    }

    @Override
    public Boolean selectWhetherAvailable(Integer id) {
        Goods goods = this.goodsMapper.selectById(id);
        if (goods.getAvailable().equals(1)){
            return false;
        }
        return true;
    }

    /**
     * 批量下架
     * @param idsList
     */
    @Override
    public void downByIds(List<Integer> idsList, String name) {
        this.goodsMapper.downByIds(idsList, name);
    }

    /**
     * 下架
     * @param id
     */
    @Override
    public void downById(Integer id, String name) {
        this.goodsMapper.downById(id,name);
    }


    /**
     * 库存预警
     * @return
     */
    public boolean warning(){
        Date date = new Date();
        int isDate = 0;
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        List<Goods> list = this.goodsMapper.selectList(queryWrapper);
        for (Goods goods : list) {
            isDate = goods.getExpiration().compareTo(date);
            if (isDate<0){//过期 优先程度高于预警直接建议退货或者报废并预警
                Notice notice0 = new Notice();
                notice0.setCreatetime(date);
                notice0.setOpername("自管理系统");
                notice0.setTitle("关于商品："+goods.getGoodsname()+"(商品编号："+goods.getId()+")过期处理通知");
                notice0.setContent("商品："+goods.getGoodsname()+"\n商品编号："+goods.getId()+"\n生产批号："+goods.getProductcode()
                        +"\n批准文号："+goods.getPromitcode()+"\n规格："+goods.getSize()+"("+goods.getGoodspackage()+")\n该商品的生产日期为："
                        +goods.getProductiondate()+"\n            现已过期，请及时清理过期库存并重新进货！");
                this.noticeMapper.insert(notice0);
                return true;
            }else { //未过期
                if (goods.getNumber() <= goods.getDangernum()){ //到达预警库存
                    Notice notice1 = new Notice();
                    notice1.setCreatetime(date);
                    notice1.setOpername("自管理系统");
                    notice1.setTitle("关于商品："+goods.getGoodsname()+"(商品编号："+goods.getId()+")过期处理通知");
                    notice1.setContent("商品："+goods.getGoodsname()+"\n商品编号："+goods.getId()+"\n生产批号："+goods.getProductcode()
                            +"\n批准文号："+goods.getPromitcode()+"\n规格："+goods.getSize()+"("+goods.getGoodspackage()+")\n该商品的生产日期为："
                            +goods.getProductiondate()+"\n            该货物库存数量已到达预警值，请及时补充库存！");
                    this.noticeMapper.insert(notice1);
                    return true;
                }
            }
        }
        return false;
    }


    @Override
    public Goods getById(Serializable id) {
        return super.getById(id);
    }

    @CacheEvict(cacheNames = "com.green.business.service.impl.GoodsServiceImpl",key = "#id")
    @Override
    public boolean removeById(Serializable id) {
        return super.removeById(id);
    }

    @Override
    public boolean removeByIds(Collection<? extends Serializable> idList) {
        return super.removeByIds(idList);
    }
}
